<template>
  <form id="raForm">
    <fieldset>
      <legend><span>基本信息</span></legend>
      <div @click="showDriverList">
        <label>驾驶人</label>
        <input type="text" placeholder="驾驶人(必选)" id="driver" readonly required tips="驾驶人" v-model="raFormInfo.driverName">
        <span class="ion ion-chevron-down"></span>
      </div>
      <div v-if="raFormInfo.expireDate">
        <label>驾照有效日期</label>
        <input type="text" placeholder="驾照有效日期" readonly v-model="raFormInfo.expireDate">
      </div>
      <div>
        <label>观察时间</label>
        <input type="date" placeholder="观察时间" v-model="raFormInfo.raTime">
      </div>
      <div>
        <label>地点</label>
        <input type="text" placeholder="地点(必填)" required tips="地点" v-model="raFormInfo.raSite">
      </div>
      <div>
        <label>天气状况</label>
        <input type="text" placeholder="天气状况" required readonly tips="天气状况" id="weather" v-model="raFormInfo.weatherName"
               @click="showCheckList($event)">
      </div>
      <div>
        <label>交通状况</label>
        <input type="text" placeholder="交通状况" required readonly tips="交通状况" id="traffice" v-model="raFormInfo.trafficeName"
               @click="showCheckList($event)">
      </div>
      <div>
        <label>道路类型</label>
        <input type="text" placeholder="道路类型" required readonly tips="道路类型" id="roadType" v-model="raFormInfo.roadTypeName"
               @click="showCheckList($event)">
      </div>
      <div>
        <label>道路状况</label>
        <input type="text" placeholder="道路状况" required readonly tips="道路状况" id="roadName" v-model="raFormInfo.roadName"
               @click="showCheckList($event)">
      </div>
      <div>
        <label>记录人</label>
        <input type="text" readonly v-model="raFormInfo.rememberName">
      </div>
      <div>
        <label>部门名称</label>
        <input type="text" readonly v-model="raFormInfo.depName">
      </div>
    </fieldset>
    <fieldset v-for="(fourAItem, index1) of raFormEdite.raInfo">
      <legend><span>{{fourAItem.typeName}}</span></legend>
      <ul class="fourAanswer">
        <li v-for="(dataItem, index2) of fourAItem.dataList">
          <h3>{{dataItem.dataContent}}</h3>
          <label v-for="(item, index) of raFormEdite.selectInfo">
            <input type="radio" class="fourAradio"
                   :id="dataItem.id+ '-' + item.typeKey"
                   :name="index1.toString() + index2.toString()"
                   :value="item.typeKey"
                   :checked="index == dataItem.dataIndex"
                   @change="fourAchoice(index1, index2, index)">
            <span class="ra_indent">
                <span v-if="item.typeName == '表现良好'" class="fc_green">{{item.typeName}}</span>
                <span v-if="item.typeName == '需改进'" class="fc_red">{{item.typeName}}</span>
                <span v-if="item.typeName == '不适用'">{{item.typeName}}</span>
            </span>
          </label>
        </li>
      </ul>
    </fieldset>
    <fieldset>
      <legend><span>评估者评语(必填)</span></legend>
      <div class="textBox">
        <textarea rows="5" placeholder="评估者评语" required tips="评估者评语" id="raComment" v-model="raFormInfo.raComment"></textarea>
      </div>
    </fieldset>
    <fieldset v-show="raState">
      <legend><span>驾驶员反馈</span></legend>
      <div class="textBox">
        <textarea rows="5" placeholder="驾驶员反馈" id="raFeedback" v-model="raFormInfo.raFeedback"></textarea>
      </div>
    </fieldset>
    <fieldset>
      <legend><span>图片</span></legend>
      <div class="upload-img-box">
        <div class="extraDiv">
          <div class="add-imgBox" v-for="(item, index) of opinionImgs">
            <img :src="item" alt="上传的图片" @click="previewImg(item)">
            <i class="ion ion-ios-close" @click="delImg(index)" v-if="!raState"></i>
          </div>
          <div class="add-imgBox">
            <div id="chooseImages" class="companypic" @click="getImg" v-if="!raState && opinionImgs.length < 6">
              <i class="ion ion-android-add fontcompany"></i>
             <!--  <span class="bluecolor block">点击上传照片</span> -->
            </div>
          </div>
        </div> 
        <div class="remark" v-if="!raState">注：车体外观和仪表盘公里数，需要各拍一张</div>
      </div>
    </fieldset>
    <div class="savebtn" v-if="!raState && isRemember">
            <button type="button" class="" @click="saveRA(0)">保存</button>
            <button type="button" class="" @click="saveRA(1)">保存并提交</button>
    </div>
<!--     <div class="weui-btn-area">
      <a class="weui-btn weui-btn_primary btn-block" href="javascript:;" @click="saveRA(0)">保存</a>
      <a class="weui-btn weui-btn_primary btn-block" href="javascript:;" @click="saveRA(1)">保存</a>
    </div> -->
    <div class="savebtn" v-if="raState && !isRemember && $route.query.state == 1">
            <button type="button" class="" @click="saveRA(3)">保存</button>
            <button type="button" class="" @click="saveRA(2)">保存并提交</button>
    </div>
   <!--  <div class="weui-btn-area" v-if="!raState && !isRemember">
      <a class="weui-btn weui-btn_primary" href="javascript:;" @click="saveRA(1)">保存</a>
      <a class="weui-btn weui-btn_primary" href="javascript:;" @click="saveRA(2)">保存并提交</a>
    </div> -->

    <!--选择列表-->
    <check-list v-if="checkListShow" :check-list-title="checkListTitle" @close="closeCheckList">
      <p v-for="(item, index) of checkListItem">
        <label>
          <input type="radio" name="checkItem" :value="item.typeKey" v-model="checkedKey" @change="choose(index)">
          <span>{{item.typeName}}</span>
        </label>
      </p>
    </check-list>
    <!--正在加载提示框-->
    <loading v-if="loadShow"></loading>
    <!--用户列表框-->
    <driver-list :dep-id="raFormInfo.depId" v-if="driverListShow" @chooseDirver="chooseDirver"
                 @close="driverListShow = false"></driver-list>
    <!--加载失败弹框-->
    <dialog-box :message="dialogMessage" v-if="dialogShow" @close-dialog="closeDialog"
                @cancle-dialog="closeDialog"></dialog-box>
    <!--表单发送成功提示框-->
    <toast v-show="toastShow"></toast>
    <!--表单验证时的提示框-->
    <transition name="slide">
      <tips v-show="tipsShow" :tips="tipsMessage"></tips>
    </transition>
  </form>
</template>
<script type="text/javascript">
  import '../../assets/css/raDetail.scss'
  import wx from 'weixin-js-sdk'
  import jssdk from '../../assets/js/jssdk/wxJSSDK'
  import interfaceAPI from '../../assets/js/insterface.js';
  import http from '../../assets/js/http_mixin'
  import getQuery from '../../assets/js/get_querys'
  import driverList from '../../widget/driverList.vue';
  import vaild from '../../assets/js/vaild_form';
  var raDetailUrl = interfaceAPI.raDetailUrl;
  var raInfoUrl = interfaceAPI.raInfoUrl;
  var raSendData = interfaceAPI.raSendData;
  export default {
    data () {
      return {
        idx: 0,
        isEdite: false,                // 判断页面是编辑查看还是新建
        isRemember: true,             // 判断是记录者查看还是被RA的人查看, 记录者者查看为true
        opinionImgs: [],              // 图片
        missImgs: [],                 // 发送给后台的图片地址
        driverListShow: false,       // 司机列表是否显示
        raState: !!this.$route.query.state,      // 根据上一页面传递过来的状态，判断页面元素的显示和隐藏
        // 表单详细信息
        raFormInfo: {
          id: '',                      // ra的ID，新建时为空
          employeeSn: '',             // 记录人code
          rememberName: '',           // 记录人name
          driverId: '',               // 驾驶人id
          driverName: '',             // 驾驶人
          depId: '',                   // 部门id
          depName: '',                // 部门名称
          expireDate: '',             // 驾照有效日期
          raTime: '',                  // 事发事件
          raSite: '',                 // 地点
          weatherCode: '',            // 天气code
          weatherName: '',            // 天气名称
          trafficeCode: '',            // 交通code
          trafficeName: '',           // 交通名称
          roadTypeCode: '',           // 道路类型Code
          roadTypeName: '',           // 道路类型名称
          roadCode: '',               // 道路状况Code
          roadName: '',                // 道路状况名称
          raComment: '',               // 评论
          raFeedback: ''                // 反馈
        },
        raFormEdite: {},              // 保存请求来的表单编辑数据
        checkListItem: [],            // 选项框的内容
        checkedKey: '',               // 最终选定的key值
        cID: '',                      // 储存打开选择框的id
        // 查看时4A问题
        fourAanswer: [],
        // 查看时4A 答案选项
        fourAnswerItem: [],
        // 查看时4A问题选项
        selectInfo: [],
        // 编辑时4A问题的选项
        fourAedite: [],
        // 编辑时4A问题选定的答案
        fourChecked: ''
      }
    },
    mixins: [jssdk, http, getQuery, vaild],
    mounted() {
      this.init();
      document.title = 'RA';
      var query = this.getQuerys();
      this.personalId = query.empNo;
      // 获取表单信息
      this.getRAForm();
      // 判断编辑状态
      var id = this.$route.query.id;
      var state = this.$route.query.state;
      id ? this.isEdite = true : this.isEdite = false;
      if (!id) {
        const d = new Date();
        var months = d.getMonth() + 1;
        var days =  d.getDate();
        if(months < 10){
          months = '0' + months;
        }
        if(days < 10){
          days = '0' + days;
        }
        this.raFormInfo.raTime = d.getFullYear()+"-"+months+"-"+days;
      }
    },
    components: {
      driverList
    },
    methods: {
      // 显示各选择框
      showCheckList(event){
        var target = event.target;
        switch (target.id) {
          case 'weather':
            this.cID = 'weather';
            this.checkListTitle = '天气状况';
            this.checkListItem = this.raFormEdite.weatherName;
            break;
          case 'traffice':
            this.cID = 'traffice';
            this.checkListTitle = '交通状况';
            this.checkListItem = this.raFormEdite.trafficeName;
            break;
          case 'roadType':
            this.cID = 'roadType';
            this.checkListTitle = '道路类型';
            this.checkListItem = this.raFormEdite.roadTypeName;
            break;
          case 'roadName':
            this.cID = 'roadName';
            this.checkListTitle = '道路状况';
            this.checkListItem = this.raFormEdite.roadName;
            break;
        }
        this.checkListShow = true;
        // 消除进入列表即有选中项的bug
        this.$nextTick(function () {
          var oCheckItem = window.document.getElementsByName('checkItem');
          for (var i = 0; i < oCheckItem.length; i++) {
            oCheckItem[i].checked = false;
          }
        })
      },

      // 显示员工选择框
      showDriverList(){
        this.driverListShow = true;
      },

      //选择员工
      chooseDirver(){
        // 获取选定的员工的id 名字  驾照日期
        var arg = arguments[0];
        this.raFormInfo.driverId = arg.employeeSn;
        this.raFormInfo.driverName = arg.employeeName;
        if (arg.expireDate) {
          this.raFormInfo.expireDate = arg.expireDate;
        } else {
          this.raFormInfo.expireDate = "";
          this.dialogMessage = '该用户没有驾驶证！';
          this.dialogShow = true;
        }
        this.driverListShow = false;
      },

      // 选择条目
      choose(index){
        switch (this.cID) {
          case 'weather':
            this.raFormInfo.weatherName = this.checkListItem[index].typeName;
            this.raFormInfo.weatherCode = this.checkedKey;
            break;
          case 'traffice':
            this.raFormInfo.trafficeName = this.checkListItem[index].typeName;
            this.raFormInfo.trafficeCode = this.checkedKey;
            break;
          case 'roadType':
            this.raFormInfo.roadTypeName = this.checkListItem[index].typeName;
            this.raFormInfo.roadTypeCode = this.checkedKey;
            break;
          case 'roadName':
            this.raFormInfo.roadName = this.checkListItem[index].typeName;
            this.raFormInfo.roadCode = this.checkedKey;
            break;
        }
        this.checkListShow = false;
      },
      // 4A问题选择
      fourAchoice(index1, index2, index){
        var radio = window.document.getElementsByName(index1.toString() + index2.toString());
        var value, i, len = radio.length;
        for (i = 0; i < len; i++) {
          if (radio[i].checked) {
            value = radio[i].value;
          }
        }
        var result = this.raFormEdite.raInfo[index1].dataList[index2].id + '-' + value;
        // 去除数组中同一个问题的答案
        this.fourAedite.forEach(function (val, index, array) {
          var arr1 = val.split('-');
          var arr2 = result.split('-');
          if (arr1[0] == arr2[0]) {
            array.splice(index, 1, result);
          }
        })
        //缓存选择的答案，防止上传图片时页面刷新，显示不正确
        this.raFormEdite.raInfo[index1].dataList[index2].dataIndex = index;
      },

      getRAForm(){
        // 获取表单信息,id值存在时，请求详情信息接口，id值不存在时，请求选项信息接口

        var id = this.$route.query.id;
        if (id === undefined) {
          this.getInfo({
            url: raInfoUrl,
            param: {
              'empNo': this.$route.query.empNo
            },
            success: function (response) {
              // debugger;
              var body = response.body;

              this.raFormEdite = body;
              this.setDataIndex();
              // 给记录人赋值
              this.raFormInfo.rememberName = body.empInfo.employeeName;
              this.raFormInfo.employeeSn = body.empInfo.employeeSn;

              // 给部门赋值
              this.raFormInfo.depId = body.empInfo.depId;
              this.raFormInfo.depName = body.empInfo.depName;

              // 获取radio框选定项
              this.$nextTick(function () {
                this.getChecked();
                this.toggleCurrent();
                this.setDisabed();
              });

              //默认第一个

              //天气
              this.raFormInfo.weatherName = body.weatherName[0].typeName;
              this.raFormInfo.weatherCode = body.weatherName[0].typeKey;

              //交通状况
              this.raFormInfo.trafficeName = body.trafficeName[0].typeName;
              this.raFormInfo.trafficeCode = body.trafficeName[0].typeKey;

              //道路类型
              this.raFormInfo.roadTypeName = body.roadTypeName[0].typeName;
              this.raFormInfo.roadTypeCode = body.roadTypeName[0].typeKey;

              //道路状况
              this.raFormInfo.roadName = body.roadName[0].typeName;
              this.raFormInfo.roadCode = body.roadName[0].typeKey;
            },
            fail: function (response) {
              this.dialogMessage = '请求失败，请稍后再试';
              this.dialogShow = true;
            }
          });
        } else {
          this.getInfo({
            url: raDetailUrl,
            param: {
              'id': this.$route.query.id
            },
            success: function (response) {
              var _this = this;
              var body = response.body;
              this.raFormEdite = body;         // 保存请求来的所有值
              this.setDataIndex();
              this.raFormInfo.id = body.raVO.id;  
              this.raFormInfo.expireDate =  body.raVO.expireDate;                    // ra ID
              this.raFormInfo.employeeSn = body.raVO.rememberNo;             // 记录人code
              this.raFormInfo.rememberName = body.raVO.rememberName;       // 记录人name
              this.raFormInfo.driverId = body.raVO.driverNo;                 // 驾驶人id
              this.raFormInfo.driverName = body.raVO.driverName;             // 驾驶人
              this.raFormInfo.depId = body.raVO.depId;                         // 部门id
              this.raFormInfo.depName = body.raVO.depName;                     // 部门名称
              this.raFormInfo.expireDate = body.raVO.expireDate;             // 驾照有效日期
              this.raFormInfo.raTime = body.raVO.raTime;                       // 事发事件
              this.raFormInfo.raSite = body.raVO.raSite;                       // 地点
              this.raFormInfo.weatherCode = body.raVO.weatherState;            // 天气code
              this.raFormInfo.weatherName = body.raVO.weatherName;            // 天气名称
              this.raFormInfo.trafficeCode = body.raVO.trafficeState;         // 交通code
              this.raFormInfo.trafficeName = body.raVO.trafficeName;           // 交通名称
              this.raFormInfo.roadTypeCode = body.raVO.roadType;               // 道路类型Code
              this.raFormInfo.roadTypeName = body.raVO.roadTypeName;           // 道路类型名称
              this.raFormInfo.roadCode = body.raVO.roadState;                  // 道路状况Code
              this.raFormInfo.roadName = body.raVO.roadName;                   // 道路状况名称
              this.raFormInfo.raComment = body.raVO.raComment;                // 评论
              this.raFormInfo.raFeedback = body.raVO.raFeedback;              // 反馈
              if (body.raVO.raImg) {
                this.opinionImgs = body.raVO.raImg.split(',');      // 图片信息
                this.missImgs = body.raVO.raImg.split(',');      // 图片信息
              }
              // 获取radio框选定项
              this.$nextTick(function () {
                this.getChecked();
                this.toggleCurrent();
                this.setDisabed();
              })
            },
            fail: function (response) {
              this.dialogMessage = '请求失败，请稍后再试';
              this.dialogShow = true;
            }
          });
        }
      },
      // 给4A问题添加一个dataIndex属性，用以判断哪个input框选中
      setDataIndex(){
        var _this = this;
        this.raFormEdite.raInfo.forEach(function (val, index) {
          val.dataList.forEach(function (value, dataIndex) {
            if (_this.isEdite) {
              // 与答案字段的typekey保持一致
              switch (value.dataResult) {
                case '1':
                  _this.$set(value, 'dataIndex', 0);
                  break;
                case '2':
                  _this.$set(value, 'dataIndex', 2);
                  break;
                case '3':
                  _this.$set(value, 'dataIndex', 1);
                  break;
              }
            } else {
              _this.$set(value, 'dataIndex', 0);
            }
          })
        })
      },
      // fieldset切换current类
      toggleCurrent(){
        var oRaForm = window.document.getElementById('raForm');
        var oFieldList = oRaForm.getElementsByTagName('fieldset');
        var i, len = oFieldList.length;
        for (i = 0; i < len; i++) {
          oFieldList[i].setAttribute('index', i);
          var oLegend = oFieldList[i].getElementsByTagName('legend')[0];
          oFieldList[0].classList.add('current');
          oLegend.onclick = function () {
            var parent = this.parentNode;
            var index = +parent.getAttribute('index');
            var siblings = parent.parentNode.children;
            var fieldset = [];
            for (var k = 0; k < siblings.length; k++) {
              if (siblings[k].tagName.toLowerCase() == 'fieldset') {
                fieldset.push(siblings[k]);
              }
            }
            fieldset.splice(index, 1);
            for (var j = 0; j < fieldset.length; j++) {
              fieldset[j].classList.remove('current');
            }
            parent.classList.toggle('current');
          }
        }
      },
      // 不能编辑时，所有的input，textarea设置为disabled
      setDisabed(){
        var oRaForm = window.document.getElementById('raForm');
        var id = this.$route.query.id;
        var state = this.$route.query.state;
        var oInput = oRaForm.getElementsByTagName('input');
        var oTextarea = oRaForm.getElementsByTagName('textarea');
        var empNo = this.$route.query.empNo;
        // debugger;
        if (empNo == this.raFormInfo.employeeSn || !empNo) {
          this.isRemember = true;
        } else{
          this.isRemember = false;
        }
        // debugger;
        if (!id) {
          window.document.getElementById('raFeedback').disabled = true;
        } else if (id && state == '1' && this.isRemember) {
          for (var i = 0; i < oInput.length; i++) {
            oInput[i].disabled = true;
          }
          for (var j = 0; j < oTextarea.length; j++) {
            oTextarea[j].disabled = true;
          }
        } else if (this.isRemember && id && state == '0') {
          window.document.getElementById('driver').disabled = true;
          window.document.getElementById('raFeedback').disabled = true;
        } else if (!this.isRemember && id && state == '1') {
          for (var i = 0; i < oInput.length; i++) {
            oInput[i].disabled = true;
          }
          for (var j = 0; j < oTextarea.length; j++) {
            oTextarea[j].disabled = true;
          }
          window.document.getElementById('raFeedback').disabled = false;
        } else if(!this.isRemember && id &&  state == '2'){
          for (var i = 0; i < oInput.length; i++) {
            oInput[i].disabled = true;
          }
          for (var j = 0; j < oTextarea.length; j++) {
            oTextarea[j].disabled = true;
          }
        }
      },
      // 获取默认的表单选定项
      getChecked(){
        var oFourAradio = window.document.querySelectorAll('.fourAradio');
        var i, len = oFourAradio.length;
        for (i = 0; i < len; i++) {
          if (oFourAradio[i].checked) {
            var id = oFourAradio[i].id;
            this.fourAedite.push(id);
          }
        }
      },
      // 选取图片
      getImg(){
        var _this = this;
        var chooseImageID = [];
        this.imageApi({
          chooseImage: {
            count: 6 - _this.opinionImgs.length,
            success: function (res) {
              chooseImageID = res.localIds;
              for (var i = 0; i < chooseImageID.length; i++) {
                _this.opinionImgs.push(chooseImageID[i]);
              }
              _this.syncUpload(chooseImageID);
            }
          }
        })
      },
      // 预览图片
      previewImg(img){
        var _this = this;
        this.imageApi({
          previewImage: {
            current: img,
            urls: _this.opinionImgs
          }
        })
      },
      // 上传图片
      syncUpload(localIds){
        var _this = this;
        this.imageApi({
          uploadImage: {
            localId: localIds[_this.idx].toString(),
            success: function (res) {
              _this.idx++;
              _this.missImgs.push(res.serverId);
              if (_this.idx < localIds.length) {
                _this.syncUpload(localIds);
              } else {
                _this.idx = 0;
              }
            }
          }
        })
      },
      delImg(index){
        this.missImgs.splice(index, 1);
        this.opinionImgs.splice(index, 1);
      },

      // 保存或者提交
      saveRA(flag){
        // flag为0时是保存，为1时是提交
        var oInput = document.getElementsByTagName('input');
        var oTextArea = document.getElementsByTagName('textarea');
        console.log(flag==2);
        if (flag==(2||3)){
          if (this.raFormInfo.raFeedback==null||this.raFormInfo.raFeedback.trim()=='') {
            var _this = this;
            this.tipsMessage = '意见反馈不能为空';
            this.tipsShow = true;
            window.setTimeout(function () {
              /*两秒后，弹窗消失*/
              _this.tipsShow = false;
              _this.tipsMessage = '';
            }, 2000);
            return false;
          } 
        }else if(flag==1){
          if (!this.vaildForm(oInput)) {
            return false
          }
          if (!this.vaildForm(oTextArea)) {
            return false
          }
        }
        
        // if (!this.missImgs.length) {
        //   var _this = this;
        //   this.tipsMessage = '必须上传图片';
        //   this.tipsShow = true;
        //   window.setTimeout(function () {
        //     /*两秒后，弹窗消失*/
        //     _this.tipsShow = false;
        //     _this.tipsMessage = '';
        //   }, 2000);
        //   return false;
        // }
        flag = flag==3? 1 : flag;
        this.getInfo({
          url: raSendData,
          param: {
            state: flag,
            id: this.raFormInfo.id,
            rememberNo: this.raFormInfo.employeeSn,
            driverNo: this.raFormInfo.driverId,
            depId: this.raFormInfo.depId,
            expireDate: this.raFormInfo.expireDate,
            raSite: this.raFormInfo.raSite,
            raTime: this.raFormInfo.raTime,
            weatherState: this.raFormInfo.weatherCode,
            trafficeState: this.raFormInfo.trafficeCode,
            roadType: this.raFormInfo.roadTypeCode,
            roadState: this.raFormInfo.roadCode,
            raComment: this.raFormInfo.raComment,
            tollerlist: this.fourAedite,
            raImg: this.missImgs.join(','),
            raFeedback: this.raFormInfo.raFeedback
          },
          success: function (response) {
            window.history.back();
            return false;
          },
          fail: function (response) {
            this.dialogMessage = '请求失败，请稍后再试';
            this.dialogShow = true;
          }
        });
      }
    }
  }
</script>
